package me.chan.chatting.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import me.chan.chatting.server.factory.GroupServiceFactory;
import me.chan.chatting.server.model.Group;
import me.chan.chatting.server.msg.GroupJoinRequestMessage;
import me.chan.chatting.server.msg.GroupJoinResponseMessage;

import java.util.Objects;

@Slf4j
@ChannelHandler.Sharable
public class GroupJoinInboundHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String username = msg.getUsername();
        Group group = GroupServiceFactory.getInstance().joinMember(groupName, username);

        if (Objects.isNull(group)) {
            ctx.writeAndFlush(new GroupJoinResponseMessage(false,
                    "The group "+ msg.getGroupName() + " is not existed"));
            return ;
        }

        ctx.writeAndFlush(new GroupJoinResponseMessage(true,
                "you have joined the group "+msg.getGroupName()));
    }
}
